/**
 * Created by zhulizhe on 2017/8/16.
 */
import React, {Component} from 'react';
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    FlatList,
    Animated,
    Dimensions,
} from 'react-native';
import {observable, action, computed, observe} from 'mobx'
import {observer} from 'mobx-react/native'
import {PriceLabel} from '../../../js/home/ShoppingCart'
import QuickPay from '../../../js/home/QuickPay'
import {SignOrder} from '../../../js/order/OrderNet'
import OrderStore from '../../../js/order/OrderListStore'
import ScrollableTabView from 'react-native-scrollable-tab-view';
import {ActionSheetCustom as ActionSheet} from 'react-native-actionsheet'
import Constant from "../../../js/Contant";

let ScreenHeight = Dimensions.get('window').height;
let ScreenWidth = Dimensions.get('window').width;

const actionParam = {
    orderId: 0,
    status: '',
    totalPayRmb: 0
};
const CANCEL_INDEX = 0;
const DESTRUCTIVE_INDEX = 1;
const options = ['取消', '确定'];
const title = '您确定签收该订单吗？';

//顶部选择栏
const OrderSelectView = React.createClass({
    propType: {
        goToPage: React.PropTypes.func,
        activeTab: React.PropTypes.number,
        tabs: React.PropTypes.array,
        tabStyle: View.propTypes.style,
        underlineStyle: View.propTypes.style,
    },
    render() {
        const backS = {
            flexDirection: 'row',
            justifyContent: 'space-between',
            height: 45,
            alignItems: 'center'
        };
        const btnS = {
            height: 45,
            width: ScreenWidth / 4,
            justifyContent: 'center',
            alignItems: 'center'
        };
        const tabUnderlineStyle = {
            position: 'absolute',
            width: ScreenWidth / 4,
            height: 3,
            backgroundColor: '#4dc0ff',
            bottom: 0,
            borderRadius: 1.5,
        };
        const left = this.props.scrollValue.interpolate({
            inputRange: [0, 1,], outputRange: [0, ScreenWidth / 4,],
        });
        return <View style={backS}>
            {this.props.tabs.map((tab, i) => {
                let textColor = this.props.activeTab == i ? '#4dc0ff' : '#333333';
                return <TouchableOpacity style={btnS}
                                         activeOpacity={1}
                                         onPress={() => {
                                             this.props.goToPage(i);
                                         }}
                                         key={tab}>
                    <Text style={{color: textColor}}>{tab}</Text>
                </TouchableOpacity>
            })}
            <Animated.View style={[tabUnderlineStyle, {left,}]}/>
        </View>
    }
});

//商品cell
export class OrderProductCell extends Component {
    render() {
        let {
            currentPrice,
            name,
            volume,
            selectCount,
            productImage
        } = this.props.product;
        return <View>
            <View style={OrderCellStyle.imageViewS}>
                <Image style={OrderCellStyle.imageS} source={{uri: productImage[0]}}/>
                <View style={OrderCellStyle.contentS}>
                    <View>
                        <Text style={{color: 'rgba(51,51,51,1)'}}>{name}</Text>
                        <Text style={{marginTop: 4, fontSize: 12, color: 'rgba(119,119,119,1)'}}>{volume}</Text>
                    </View>
                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                        <PriceLabel price={currentPrice}/>
                        <Text style={{fontSize: 14.5, color: 'rgba(51,51,51,1)'}}>
                            <Text style={{fontSize: 12.5}}> x </Text>{selectCount + ''}</Text>
                    </View>
                </View>
            </View>
            <View style={OrderCellStyle.lineS}/>
        </View>
    }
}

//订单cell
@observer
class OrderCell extends Component {
    actionParamAssign(param) {
        actionParam.orderId = param.orderId;
        actionParam.status = param.status;
        actionParam.totalPayRmb = param.totalPayRmb;
    }

    render() {
        let order = this.props.data.item;
        let rightText = '';
        if (order.status == '待付款') {
            rightText = '去支付';
        } else if (order.status == '待收货') {
            rightText = '去签收';
        } else if (order.status == '待评价') {
            rightText = '去评价'
        }
        // let rightText = order.status == '待付款' ? '去支付' : order.status == '待收货' ? '签收' : '评价';
        let param = {
            orderId: order.orderId,
            orderNo: order.orderNo,
            status: order.status,
            totalPayRmb: order.totalPayRmb
        };
        let praiseParam = {
            orderId: order.orderId,
            shopId: order.shopId,
            deliveryId: order.deliveryId,
            productModels: order.productItemModels
        };
        return <TouchableOpacity style={{backgroundColor: 'rgba(241,241,243,1)'}}
                                 activeOpacity={1}
                                 onPress={() => {
                                     this.props.detailPress(param)
                                 }}>
            {/*店铺信息*/}
            <View style={OrderCellStyle.topViewS}>
                <View style={{flexDirection: 'row', height: 15, alignItems: 'center'}}>
                    <Image style={{marginLeft: 12, height: 15, width: 15}}
                           source={require('../../../luoasserts/tab/tab_icon_water_station_s.png')}/>
                    <Text style={{marginLeft: 3, color: 'rgba(119,119,119,1)'}}>{order.shopName}</Text>
                </View>
                <Text style={{marginRight: 12, color: 'rgba(77,192,255,1)'}}>{order.status}</Text>
            </View>
            <View style={OrderCellStyle.lineS}/>

            {/*商品列表*/}
            {order.productItemModels.map((product, index) => {
                return <OrderProductCell product={product} key={index}/>
            })}

            {/*支付信息(商品件数/实付款)*/}
            <View style={OrderCellStyle.backViewS}>
                <Text style={{marginRight: 12, fontSize: 12.5, color: 'rgba(119,119,119,1)'}}>共 {order.totalCount + ''}
                    件商品，实付款:</Text>
                <PriceLabel price={order.totalPayRmb} color={Constant.TEXT_COLOR_6}/>
            </View>
            <View style={OrderCellStyle.lineS}/>

            {/*操作部分(支付/签收/评论)*/}
            <View style={OrderCellStyle.backViewS}>
                {order.status=='待付款'||order.status=='待评价'||order.status == '待收货' ?
                    <TouchableOpacity style={OrderCellStyle.opeBtnS}
                                      onPress={() => {
                                          this.actionParamAssign(param);
                                          if (order.status == '待付款' || order.status == '待评价') {
                                              this.props.payPraise(param, praiseParam)
                                          } else if (order.status == '待收货') {
                                              this.props.leftAction()
                                          }
                                      }}>
                    <Text style={{color: 'rgba(77,192,255,1)'}}>{rightText}</Text>
                </TouchableOpacity> : null}
            </View>
            <View style={{flexDirection: 'row', height: 15, backgroundColor: 'rgba(241,241,243,1)'}}/>
        </TouchableOpacity>
    }
}

const OrderCellStyle = {
    topViewS: {
        flexDirection: 'row',
        height: 40,
        backgroundColor: 'white',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    backViewS: {
        flexDirection: 'row',
        height: 40,
        backgroundColor: 'white',
        justifyContent: 'flex-end',
        alignItems: 'center',
        paddingHorizontal: 10
    },
    imageViewS: {
        flexDirection: 'row',
        height: 85,
        backgroundColor: 'white',
        alignItems: 'center'
    },
    imageS: {
        flexDirection: 'row',
        marginLeft: 12,
        width: 65,
        height: 65,
        justifyContent: 'center',
        borderRadius: 4,
        alignSelf: 'center'
    },
    contentS: {
        marginLeft: 10,
        height: 58,
        justifyContent: 'space-between'
    },
    lineS: {
        flexDirection: 'row',
        height: 0.5,
        backgroundColor: 'rgba(227,227,227,1)'
    },
    opeBtnS: {
        marginRight: 2,
        width: 70,
        height: 25,
        borderRadius: 3,
        borderColor: 'rgba(77,192,255,1)',
        borderWidth: 0.5,
        justifyContent: 'center',
        alignItems: 'center'
    }
};

//无数据空组件
class OrderEmpHeader extends Component {
    render() {
        const empStyle = {
            backS: {
                height: ScreenHeight - 99,
                alignItems: 'center'
            },
            textS: {
                marginTop: (ScreenHeight - 64) / 2 - 80,
                fontSize: 13,
                color: 'rgba(119,119,119,1)'
            }
        };
        return <View style={empStyle.backS}>
            <Text style={empStyle.textS}>暂时没有相关订单</Text>
        </View>
    }
}

@observer
class OrderList extends Component {

    @observable orderA = [];

    constructor(props) {
        super(props);
        this.pageNo = 0;
    };

    componentDidMount() {
        OrderStore.refreshList(this.props.pageIndex, this.pageNo, this.props.orderStatus);
    };

    // 详情
    goToDetail(param) {
        this.props.navigation.navigate('OrderDetail', {orderParam: param})
    };

    // 去支付
    payPraiseOrder(param, praiseParam) {
        if (param.status == '待付款') {
            this.props.navigation.navigate('QuickPay', {
                orderNo: param.orderNo,
                orderId: param.orderId,
                totalPrice: param.totalPayRmb
            });
        } else if (param.status == '待评价') {
            this.props.navigation.navigate('OrderPraise', praiseParam);
        }

    };
    _getList(){
        if (this.props.pageIndex==0) {
            return OrderStore.allList;
        } else if (this.props.pageIndex==1) {
            return OrderStore.createList;
        } else if (this.props.pageIndex==2) {
            return OrderStore.deliveryList;
        } else if (this.props.pageIndex==3) {
            return OrderStore.appraiseList;
        }
    };

    _headRefresh() {
        this.pageNo = 0;
        this.orderA = [];
        OrderStore.refreshList(this.props.pageIndex, this.pageNo, this.props.orderStatus);
    };

    _keyExtractor = (item, index) => item.id;

    _renderItem = (item) => (<OrderCell data={item}
                                        id={item.id}
                                        detailPress={this.goToDetail.bind(this)}
                                        payPraise={this.payPraiseOrder.bind(this)}
                                        leftAction={this.props.cancelDelete}/>);

    _renderEmpty() {
        return <OrderEmpHeader/>
    };

    render() {
        return <FlatList onEndReachedThreshold={1}
                         data={this._getList()}
                         keyExtractor={this._keyExtractor}
                         renderItem={this._renderItem.bind(this)}
                         ListEmptyComponent={this._renderEmpty.bind(this)}
                         onRefresh={this._headRefresh.bind(this)}
                         refreshing={OrderStore.loading}
                         style={{flex: 1}}/>
    };
}

export default class OrderLuo extends Component {
    static navigationOptions = {
        title: '订单'
    };

    constructor(props) {
        super(props);
        this.state = {
            tabs: ['全部', '待付款', '待收货'],
            activeTab: 0
        };
        this.initialIndex = 0;
        if (this.props.navigation.state.params) {
            this.initialIndex = this.props.navigation.state.params.index || 0;
        }
    }

    async cancelDeleteAction() {
        if (actionParam.status == '待收货') {
            let param = {orderId: actionParam.orderId};
            let singOrder = await SignOrder(param);
            LOG('JessieJ订单签收++++++++++'+JSON.stringify(singOrder));
            if (singOrder.respMsg=='successful') {
                OrderStore.SignOrder(actionParam.orderId);
            }
        }
    }

    render() {
        return <View style={{flex: 1, backgroundColor: 'rgba(241,241,243,1)'}}>
            {this._getTab()}
            <ActionSheet ref="ActionSheet"
                         title={title}
                         options={options}
                         cancelButtonIndex={CANCEL_INDEX}
                         destructiveButtonIndex={DESTRUCTIVE_INDEX}
                         onPress={() => {
                             this.cancelDeleteAction()
                         }}/>
        </View>
    }

    _getTab() {
        let tabsA = ['全部','待付款','待收货','待评价'];
        return <ScrollableTabView initialPage={this.initialIndex}
                                  style={{height: 90}}
                                  renderTabBar={() => <OrderSelectView/>}
                                  tabBarActiveTextColor='#4dc0ff'
                                  tabBarInactiveTextColor='#333333'
                                  tabBarUnderlineStyle={{backgroundColor: '#4dc0ff', height: 2, width: 10}}>
            {tabsA.map((tab,i)=>{
                return <OrderList {...this.props} tabLabel={tab} pageIndex={i} orderStatus={tab} cancelDelete={()=>{this.refs.ActionSheet.show()}}/>
            })}
        </ScrollableTabView>
    }
}

